"""
    @Author  : Lisheng
    @Time    : 2021/3/12
    @Comment : 用于同步当天的资质证照文件，配合RPA上传到国控主数据
    配置文件说明：dbconfig.ini是程序的主要配置文件
    [DOWNLOADSET] 些估内容是设置下载相关参数
        DOWNLOADDIRNAME = F:/testdownload #下载的文件存在本地的指定目标，目录如果没有系统会自动建立
        DOWNLOADDATE = default #下载的文件所取的创建日期，默认情况下取当天的创建的文件，如果需要重新也可以
                                将期值改为指定日期格式为:xxxx-xx-xx
        DOWNLOADGSLIST = 1,16  # 需要下载的CMS的货主ID用","分隔
        RUNTIME = 0            # 指定的定时运行的时间，如RUNTIME=12，则每天12点系统会自动运行。如果需要立即
                                执行则将RUNTIME设置为0


"""
import configparser
import json
import os
import sys

import time

from ftplib import FTP
import pandas as pd
import logging.config
import pymysql
import base64
import re
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR
from apscheduler.schedulers.blocking import BlockingScheduler

cf = configparser.ConfigParser()
currentdirname, filename = os.path.split(os.path.abspath(__file__))



def init_logging(default_path="cmbbankfileconfig.json", default_level=logging.INFO, env_key="LOG_CFG"):
    """
    初始化日志记录的参数
    把日志记录的参数写入到配置文件中。
    配置文件的目录 为Config/logconfig.json
    产生的Log文件，放入至Logs目录中
    """
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, "r", encoding='utf-8') as f:
            config = json.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)


def my_listener(event):
    if event.exception:
        print('任务出错了！！！！！！')
        print(event.exception)
    else:
        print('任务照常运行...')
        print(event.exception)


def getLicensData(strgsbm, startDate=time.strftime('%Y-%m-%d')):
    """
    用于查询当天维护的资质文件记录
    :param strgsbm: 公司编码（1，16）与CMS中的OWNERID匹配
    :param startDate: 更新日期，默认为当天日期
    :return:
    """

    govdb = pymysql.connect(base64.b64decode(cf.get("MYSQL", "DB_HOST")), base64.b64decode(cf.get("MYSQL", "DB_USER")),
                            base64.b64decode(cf.get("MYSQL", "DB_PWD")), base64.b64decode(cf.get("MYSQL", "DB_NAME")))
    cr = govdb.cursor()

    strsql = " select m.gsbm,m.sphkhbm,s.ZZLXZLBM,s.fj,s.ZZWJBB from " \
             "t_lpromis_zzgl_zzxx M inner join  t_lpromis_zzgl_zzwjxx S on m.id=s.pid " \
             "where m.ENABLE =1 and m.gsbm='" + strgsbm + "' and " \
                                                          "DATE_FORMAT(s.UPDATETIME,'%Y-%m-%d') = '" + startDate + "'"

    cr.execute(strsql)
    rs = cr.fetchall()
    df = pd.DataFrame(list(rs), columns=['GSBM', 'SPHKHBM', 'ZZLXZLBM', 'FJ', 'ZZWJBB'])
    cr.close()
    govdb.close()

    return df


# 准备药检单文件，根据文件号取文件，并放入相应的目录中
def prefile(mediaDF):
    stra = ''
    ret = {}

    # 将所有准备好的文件均放在一个目录 下，该目录 下按照公司再分别建立各自的文件目录 。
    donwloadpath = cf.get("DOWNLOADSET", "DOWNLOADDIRNAME")
    if not os.path.isdir(donwloadpath):
        os.mkdir(donwloadpath)

    # ===========================================================================
    # 取对应的文件
    # ==========================================================================
    ftp = FTP(host=base64.b64decode(cf.get("FTP", "HOST_NAME")),
              user=bytes.decode(base64.b64decode(cf.get("FTP", "USER_NAME"))),
              passwd=bytes.decode(base64.b64decode(cf.get("FTP", "PASSWD"))))
    ftp.cwd(cf.get("FTP", "FILEPATH"))
    # ['GSBM', 'SPHKHBM', 'ZZLXZLBM', 'FJ', 'ZZWJBB']

    for index, row in mediaDF.iterrows():
        if len(row['FJ']) > 0:  # 有盖单的药检单
            try:
                pattern = re.compile(r'<FileID>\w+</FileID>')
                fjlist = pattern.findall(row['FJ'])
            except Exception as err:
                logging.info("解析附件XML串失败！%s" % row['FJ'])
                continue
            inx = 0
            for rw in fjlist:
                inx += 1
                ret = rw[8:-9]
                if len(ret) > 0:
                    filepath = ret[0:2] + '/' + ret[2:4] + '/' + ret[4:6] + '/' + ret
                    desfilename = donwloadpath + '\\' + row['GSBM'] + '_' + row['SPHKHBM'] + '_' + \
                                  str(row['ZZWJBB']) + "_" + row['ZZLXZLBM'] + "_" + str(inx) + '.pdf'
                    # print(desfilename)

                    fd = open(desfilename, 'wb')
                    print(filepath)
                    try:
                        ftp.retrbinary('RETR ' + filepath, fd.write, 2048)
                        fd.close()
                    except Exception as err:
                        fd.close()
                        logging.info('下载证照文件失败。文件为%s ' % desfilename)


def main():
    # 需要同步许可的公司列表,取出字符串后转换为列表
    strgsstr = cf.get("DOWNLOADSET", "DOWNLOADGSLIST")
    gslist = strgsstr.split(",")
    # 查询日期，默认为当天，如果需要重新下载某在的数据，可修改配置文件中的DOWNLOADDATE项.格式为YYYY-MM-DD
    querydate = cf.get("DOWNLOADSET", "DOWNLOADDATE")
    if querydate == "default":
        querydate = time.strftime("%Y-%m-%d")

    for item in gslist:
        df = getLicensData(item, querydate)
        prefile(df)


if __name__ == "__main__":

    # currentdirname, filename = os.path.split(os.path.abspath(__file__))
    tmp = sys.argv[0]
    print(tmp)
    print("tmp",tmp,"tmp2",tmp.rfind("/"))
    currentdirname = tmp[0:tmp.rfind("\\")]

    print("currentdirname",currentdirname)
    # print(os.get_exec_path())
    # print(currentdirname)
    # print(filename)
    # print("sys" , sys.argv[0])
    # print("cwd" , os.getcwd())

    cf.read(currentdirname+'/config/dbconfig.ini', encoding='utf-8')
    init_logging(default_path=currentdirname+"/config/cmbbankfileconfig.json")
    logging.info('系统开始运行')
    strhour = cf.get("DOWNLOADSET", "RUNTIME")

    if strhour == '0':
        main()
    else:
        scheduler = BlockingScheduler()
        scheduler.add_job(main, 'cron', hour=strhour)
        scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
        scheduler._logger = logging.getLogger()
        scheduler.start()
